<?php
require_once 'config/database.php';
session_start();

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

// 获取统计信息
$today = date('Y-m-d');
$stats = array('total' => 0, 'hammer_storage' => 0, 'delivered' => 0);

$sql = "SELECT 
            COUNT(*) as total,
            SUM(CASE WHEN production_status = '整锤入库' THEN 1 ELSE 0 END) as hammer_storage,
            SUM(CASE WHEN production_status = '发车' THEN 1 ELSE 0 END) as delivered
        FROM production_details";
$result = $conn->query($sql);

if ($result) {
    $stats = $result->fetch_assoc();
} else {
    // 如果查询失败，记录错误
    error_log("统计查询失败: " . $conn->error);
}

// 设置每页显示的记录数
$records_per_page = 50;

// 获取当前页码
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $records_per_page;

// 在PHP部分修改查询语句，添加筛选条件
$where_conditions = [];
$params = [];

if (!empty($_GET['model_number'])) {
    $where_conditions[] = "model_number LIKE ?";
    $params[] = '%' . $_GET['model_number'] . '%';
}

if (!empty($_GET['production_batch'])) {
    $where_conditions[] = "production_batch LIKE ?";
    $params[] = '%' . $_GET['production_batch'] . '%';
}

if (!empty($_GET['production_status'])) {
    $where_conditions[] = "production_status = ?";
    $params[] = $_GET['production_status'];
}

if (!empty($_GET['date_from'])) {
    $where_conditions[] = "created_at >= ?";
    $params[] = $_GET['date_from'] . ' 00:00:00';
}

if (!empty($_GET['date_to'])) {
    $where_conditions[] = "created_at <= ?";
    $params[] = $_GET['date_to'] . ' 23:59:59';
}

if (!empty($_GET['is_number_changed'])) {
    $where_conditions[] = "is_number_changed = ?";
    $params[] = $_GET['is_number_changed'];
}

if (!empty($_GET['machine_number'])) {
    $where_conditions[] = "machine_number LIKE ?";
    $params[] = '%' . $_GET['machine_number'] . '%';
}

// 构建WHERE子句
$where_clause = '';
if (!empty($where_conditions)) {
    $where_clause = 'WHERE ' . implode(' AND ', $where_conditions);
}

// 修改查询语句
$sql = "SELECT * FROM production_details $where_clause ORDER BY created_at DESC LIMIT $offset, $records_per_page";

// 使用预处理语句
$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param(str_repeat('s', count($params)), ...$params);
}
$stmt->execute();
$productionDetails = $stmt->get_result();

// 修改总记录数查询
$total_records_sql = "SELECT COUNT(*) as count FROM production_details $where_clause";
$stmt = $conn->prepare($total_records_sql);
if (!empty($params)) {
    $stmt->bind_param(str_repeat('s', count($params)), ...$params);
}
$stmt->execute();
$total_records = $stmt->get_result()->fetch_assoc()['count'];
$total_pages = ceil($total_records / $records_per_page);
?>

<!DOCTYPE html>
<html>
<head>
    <title>生产排产系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f4f4f4;
        }
        .container {
            max-width: 98%;
            margin: 0 auto;
            padding: 0 15px;
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding: 10px;
            background-color: white;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .stats-container {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }
        .stat-card {
            flex: 1;
            background-color: white;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            text-align: center;
        }
        .stat-number {
            font-size: 24px;
            font-weight: bold;
            color: #2196F3;
        }
        .section {
            background-color: white;
            padding: 20px;
            margin-bottom: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0,0,0,0.08);
        }
        .table-container {
            border: 1px solid #eef2f7;
            border-radius: 8px;
            overflow-x: auto;
        }
        table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
            font-size: 13px;
        }
        th, td {
            padding: 12px 8px;
            text-align: left;
            border-bottom: 1px solid #eef2f7;
            font-size: 14px;
            white-space: nowrap;
        }
        th:nth-child(1), td:nth-child(1) { width: 50px; }
        th:nth-child(2), td:nth-child(2) { width: 100px; }
        th:nth-child(3), td:nth-child(3) { width: 140px; }
        th:nth-child(4), td:nth-child(4) { 
            width: 130px;
        }
        th:nth-child(5), td:nth-child(5) { width: 130px; }
        th:nth-child(6), td:nth-child(6) { 
            width: 98px;
            min-width: 98px;
        }
        th:nth-child(7), td:nth-child(7) { 
            width: 42px;
            min-width: 42px;
            text-align: center;
        }
        th:nth-child(n+8):nth-child(-n+17), 
        td:nth-child(n+8):nth-child(-n+17) { 
            width: 100px;
        }
        th:last-child, td:last-child { 
            width: 140px;
        }
        th {
            padding: 12px 8px;
            font-weight: 600;
            color: #3a4a5b;
            text-transform: uppercase;
            font-size: 12px;
            letter-spacing: 0.5px;
            border-bottom: 2px solid #eef2f7;
            position: sticky;
            top: 0;
            z-index: 10;
            background-color: #f8fafc;
            text-align: center;
            white-space: normal;
            height: 50px;
            vertical-align: middle;
        }
        tr:nth-child(even) {
            background-color: #fafbfc;
        }
        tr:hover td {
            background-color: #f1f5f9;
        }
        td:empty::after {
            content: "-";
            color: #a0aec0;
        }
        .logout-btn {
            background-color: #dc3545;
            color: white;
            padding: 8px 15px;
            border: none;
            border-radius: 3px;
            text-decoration: none;
        }
        .add-btn {
            background-color: #48bb78;
            padding: 8px 16px;
            border-radius: 6px;
            font-weight: 500;
        }
        .add-btn:hover {
            background-color: #38a169;
        }
        .status-badge {
            padding: 5px 10px;
            border-radius: 15px;
            font-size: 12px;
            font-weight: bold;
        }
        .yes-no-badge {
            padding: 2px 4px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
            display: inline-block;
            min-width: 30px;
            text-align: center;
        }
        .yes-badge {
            background-color: #feb2b2;
            color: #c53030;
        }
        .no-badge {
            background-color: #9ae6b4;
            color: #276749;
        }
        .status-select {
            width: 98px;
            min-width: 98px;
            padding: 4px 2px;
            margin: 0 auto;
            display: block;
            font-size: 14px;
            text-align: center;
        }
        .status-select:hover {
            border-color: #cbd5e0;
        }
        .status-select:focus {
            outline: none;
            border-color: #4299e1;
            box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.15);
        }
        .status-select option {
            padding: 4px 2px;
            font-size: 14px;
            text-align: center;
        }
        .action-btn {
            padding: 4px 8px;
            margin: 0 2px;
            font-size: 12px;
        }
        .action-btn:hover {
            opacity: 0.85;
        }
        .edit-btn {
            background-color: #4299e1;
            color: white;
        }
        .edit-btn:hover {
            background-color: #3182ce;
        }
        .delete-btn {
            background-color: #f56565;
            color: white;
        }
        .delete-btn:hover {
            background-color: #e53e3e;
        }
        td[data-date] {
            text-align: center;
            white-space: nowrap;
        }
        /* 复选框样式 */
        input[type="checkbox"] {
            width: 14px;
            height: 14px;
            margin: 0;
            cursor: pointer;
        }
        /* 导出按钮样式 */
        .export-btn {
            background-color: #4299e1;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            font-weight: 500;
        }
        .export-btn:hover {
            background-color: #3182ce;
        }
        /* 选中行的样式 */
        tr.selected {
            background-color: #e8f4ff !important;
        }
        /* 调整第一列宽度 */
        th:first-child, td:first-child {
            width: 50px;
            padding: 8px 4px;
            text-align: center;
        }
        /* 复选框容器样式 */
        td:first-child div {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 4px;
        }
        /* 序号文本样式 */
        td:first-child span {
            font-size: 13px;
            color: #666;
        }
        /* 表格标题区域 */
        .table-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #eef2f7;
        }
        .table-header h2 {
            margin: 0;
            color: #2c3e50;
            font-size: 1.5rem;
        }
        /* 表格滚动条美化 */
        .table-container::-webkit-scrollbar {
            height: 8px;
        }
        .table-container::-webkit-scrollbar-track {
            background: #f7fafc;
            border-radius: 4px;
        }
        .table-container::-webkit-scrollbar-thumb {
            background: #cbd5e0;
            border-radius: 4px;
        }
        .table-container::-webkit-scrollbar-thumb:hover {
            background: #a0aec0;
        }
        /* 表格内容溢出处理 */
        td {
            padding: 8px;
            text-align: center;
            vertical-align: middle;
        }
        /* 鼠标悬停时显示完整内容 */
        td:hover {
            overflow: visible;
            white-space: normal;
            position: relative;
            z-index: 1;
        }
        /* 非管理员状态显示样式 */
        td:nth-child(6) {
            text-align: center;
            padding: 8px 2px;
        }
        /* 如果需要添加下拉列表样式（可选） */
        .change-number-select {
            width: 42px;
            padding: 2px;
            border: 1px solid #e2e8f0;
            border-radius: 4px;
            font-size: 12px;
            text-align: center;
            background-color: transparent;
        }
        .change-number-select option[value="否"] {
            background-color: #9ae6b4;
            color: #276749;
        }
        .change-number-select option[value="是"] {
            background-color: #feb2b2;
            color: #c53030;
        }
        .pagination {
            display: flex;
            justify-content: center;
            gap: 5px;
            margin-top: 20px;
        }
        .page-link {
            padding: 8px 12px;
            border: 1px solid #e2e8f0;
            border-radius: 4px;
            color: #4a5568;
            text-decoration: none;
            transition: all 0.2s;
        }
        .page-link:hover {
            background-color: #f7fafc;
        }
        .page-link.active {
            background-color: #4299e1;
            color: white;
            border-color: #4299e1;
        }
        .filter-section {
            background-color: white;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 15px;
            box-shadow: 0 2px 12px rgba(0,0,0,0.08);
        }
        .filter-form {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .filter-group {
            display: flex;
            align-items: center;
            gap: 8px;
            min-width: auto;
        }
        .filter-group label {
            font-size: 13px;
            color: #4a5568;
            font-weight: 500;
            white-space: nowrap;
            margin: 0;
        }
        .filter-input, .filter-select {
            padding: 4px 8px;
            border: 1px solid #e2e8f0;
            border-radius: 4px;
            font-size: 13px;
            width: 120px;
            transition: all 0.2s;
        }
        .date-range {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .date-inputs {
            display: flex;
            align-items: center;
            gap: 4px;
        }
        .date-inputs input[type="date"] {
            width: 130px;
        }
        .date-separator {
            color: #718096;
            font-size: 13px;
            margin: 0 2px;
        }
        .filter-buttons {
            display: flex;
            gap: 8px;
            margin-left: auto;
        }
        .filter-btn {
            padding: 4px 12px;
            height: 28px;
            font-size: 13px;
            display: flex;
            align-items: center;
        }
        /* 调整下拉框的宽度 */
        select[name="production_status"] {
            width: 100px;
        }
        select[name="is_number_changed"] {
            width: 80px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>生产排产系统</h1>
            <div>
                <span>欢迎, <?php echo htmlspecialchars($_SESSION['username']); ?></span>
                <a href="logout.php" class="logout-btn">退出登录</a>
            </div>
        </div>

        <div class="stats-container">
            <div class="stat-card">
                <h3>总生产数量</h3>
                <div class="stat-number"><?php echo $stats['total']; ?></div>
            </div>
            <div class="stat-card">
                <h3>整锤入库数量</h3>
                <div class="stat-number"><?php echo $stats['hammer_storage']; ?></div>
            </div>
            <div class="stat-card">
                <h3>已发车数量</h3>
                <div class="stat-number"><?php echo $stats['delivered']; ?></div>
            </div>
        </div>

        <div class="section">
            <div class="table-header">
                <h2>生产明细表</h2>
                <div class="table-actions">
                    <?php if ($_SESSION['role'] == 'admin'): ?>
                        <button class="export-btn" onclick="exportSelected()">
                            <i class="fas fa-file-export"></i> 导出选中
                        </button>
                        <button class="add-btn" onclick="location.href='add_detail.php'">
                            <i class="fas fa-plus"></i> 添加明细
                        </button>
                    <?php endif; ?>
                </div>
            </div>
            <div class="table-container">
                <!-- 在表格上方添加筛选区域 -->
                <div class="filter-section">
                    <form id="filterForm" class="filter-form">
                        <div class="filter-group">
                            <label>型号</label>
                            <input type="text" name="model_number" class="filter-input" placeholder="请输入型号">
                        </div>
                        
                        <div class="filter-group">
                            <label>批次</label>
                            <input type="text" name="production_batch" class="filter-input" placeholder="请输入批次">
                        </div>

                        <div class="filter-group">
                            <label>车号</label>
                            <input type="text" name="machine_number" class="filter-input" placeholder="请输入车号">
                        </div>
                        
                        <div class="filter-group">
                            <label>进度</label>
                            <select name="production_status" class="filter-select">
                                <option value="">全部</option>
                                <option value="未开始" <?php echo isset($_GET['production_status']) && $_GET['production_status'] == '未开始' ? 'selected' : ''; ?>>未开始</option>
                                <option value="预处理上线" <?php echo isset($_GET['production_status']) && $_GET['production_status'] == '预处理上线' ? 'selected' : ''; ?>>预处理上线</option>
                                <option value="预处理入库" <?php echo isset($_GET['production_status']) && $_GET['production_status'] == '预处理入库' ? 'selected' : ''; ?>>预处理入库</option>
                                <option value="机芯下线" <?php echo isset($_GET['production_status']) && $_GET['production_status'] == '机芯下线' ? 'selected' : ''; ?>>机芯下线</option>
                                <option value="机芯转涂" <?php echo isset($_GET['production_status']) && $_GET['production_status'] == '机芯转涂' ? 'selected' : ''; ?>>机芯转涂</option>
                                <option value="机芯入库" <?php echo isset($_GET['production_status']) && $_GET['production_status'] == '机芯入库' ? 'selected' : ''; ?>>机芯入库</option>
                                <option value="壳体安装" <?php echo isset($_GET['production_status']) && $_GET['production_status'] == '壳体安装' ? 'selected' : ''; ?>>壳体安装</option>
                                <option value="整锤转涂" <?php echo isset($_GET['production_status']) && $_GET['production_status'] == '整锤转涂' ? 'selected' : ''; ?>>整锤转涂</option>
                                <option value="整锤入库" <?php echo isset($_GET['production_status']) && $_GET['production_status'] == '整锤入库' ? 'selected' : ''; ?>>整锤入库</option>
                                <option value="发车" <?php echo isset($_GET['production_status']) && $_GET['production_status'] == '发车' ? 'selected' : ''; ?>>发车</option>
                            </select>
                        </div>

                        <div class="filter-group date-range">
                            <label>日期</label>
                            <div class="date-inputs">
                                <input type="date" name="date_from" class="filter-input">
                                <span class="date-separator">至</span>
                                <input type="date" name="date_to" class="filter-input">
                            </div>
                        </div>

                        <div class="filter-group">
                            <label>改号</label>
                            <select name="is_number_changed" class="filter-select">
                                <option value="">全部</option>
                                <option value="是">是</option>
                                <option value="否">否</option>
                            </select>
                        </div>

                        <div class="filter-buttons">
                            <button type="submit" class="filter-btn">筛选</button>
                            <button type="button" class="filter-btn clear" onclick="clearFilter()">清除</button>
                        </div>
                    </form>
                </div>
                <table>
                    <thead>
                        <tr>
                            <th width="50px">序号</th>
                            <th>型号</th>
                            <th>生产批次</th>
                            <th>整机编号</th>
                            <th>适配型号</th>
                            <th>生产进度</th>
                            <th style="width: 42px;">改号</th>
                            <th>预处理上线</th>
                            <th>预处理入库</th>
                            <th>机芯下线</th>
                            <th>机芯转涂</th>
                            <th>机芯入库</th>
                            <th>壳体安装</th>
                            <th>整锤转涂</th>
                            <th>整捶入库</th>
                            <th>发车</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($productionDetails->num_rows > 0): ?>
                            <?php $i = 1; while($detail = $productionDetails->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <div style="display: flex; align-items: center; justify-content: center; gap: 4px;">
                                            <input type="checkbox" class="row-checkbox" value="<?php echo $detail['id']; ?>">
                                            <span><?php echo $i++; ?></span>
                                        </div>
                                    </td>
                                    <td><?php echo htmlspecialchars($detail['model_number']); ?></td>
                                    <td><?php echo htmlspecialchars($detail['production_batch']); ?></td>
                                    <td><?php echo htmlspecialchars($detail['machine_number']); ?></td>
                                    <td><?php echo htmlspecialchars($detail['compatible_model']); ?></td>
                                    <td>
                                        <?php if ($_SESSION['role'] == 'admin'): ?>
                                            <select class="status-select" onchange="updateStatus(<?php echo $detail['id']; ?>, this.value)">
                                                <option value="未开始" <?php echo $detail['production_status'] == '未开始' ? 'selected' : ''; ?>>未开始</option>
                                                <option value="预处理上线" <?php echo $detail['production_status'] == '预处理上线' ? 'selected' : ''; ?>>预处理上线</option>
                                                <option value="预处理入库" <?php echo $detail['production_status'] == '预处理入库' ? 'selected' : ''; ?>>预处理入库</option>
                                                <option value="机芯下线" <?php echo $detail['production_status'] == '机芯下线' ? 'selected' : ''; ?>>机芯下线</option>
                                                <option value="机芯转涂" <?php echo $detail['production_status'] == '机芯转涂' ? 'selected' : ''; ?>>机芯转涂</option>
                                                <option value="机芯入库" <?php echo $detail['production_status'] == '机芯入库' ? 'selected' : ''; ?>>机芯入库</option>
                                                <option value="壳体安装" <?php echo $detail['production_status'] == '壳体安装' ? 'selected' : ''; ?>>壳体安装</option>
                                                <option value="整锤转涂" <?php echo $detail['production_status'] == '整锤转涂' ? 'selected' : ''; ?>>整锤转涂</option>
                                                <option value="整锤入库" <?php echo $detail['production_status'] == '整锤入库' ? 'selected' : ''; ?>>整锤入库</option>
                                                <option value="发车" <?php echo $detail['production_status'] == '发车' ? 'selected' : ''; ?>>发车</option>
                                            </select>
                                        <?php else: ?>
                                            <?php echo htmlspecialchars($detail['production_status']); ?>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($_SESSION['role'] == 'admin'): ?>
                                            <select class="change-number-select" onchange="updateChangeNumber(<?php echo $detail['id']; ?>, this.value)">
                                                <option value="否" <?php echo $detail['is_number_changed'] == '否' ? 'selected' : ''; ?>>否</option>
                                                <option value="是" <?php echo $detail['is_number_changed'] == '是' ? 'selected' : ''; ?>>是</option>
                                            </select>
                                        <?php else: ?>
                                            <span class="yes-no-badge <?php echo $detail['is_number_changed'] == '是' ? 'yes-badge' : 'no-badge'; ?>">
                                                <?php echo $detail['is_number_changed']; ?>
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td data-date><?php echo $detail['preprocess_online_date'] ? date('Y-m-d', strtotime($detail['preprocess_online_date'])) : '-'; ?></td>
                                    <td><?php echo $detail['preprocess_storage_date'] ? date('Y-m-d', strtotime($detail['preprocess_storage_date'])) : '-'; ?></td>
                                    <td><?php echo $detail['core_offline_date'] ? date('Y-m-d', strtotime($detail['core_offline_date'])) : '-'; ?></td>
                                    <td><?php echo $detail['core_coating_date'] ? date('Y-m-d', strtotime($detail['core_coating_date'])) : '-'; ?></td>
                                    <td><?php echo $detail['core_storage_date'] ? date('Y-m-d', strtotime($detail['core_storage_date'])) : '-'; ?></td>
                                    <td><?php echo $detail['shell_install_date'] ? date('Y-m-d', strtotime($detail['shell_install_date'])) : '-'; ?></td>
                                    <td><?php echo $detail['hammer_coating_date'] ? date('Y-m-d', strtotime($detail['hammer_coating_date'])) : '-'; ?></td>
                                    <td><?php echo $detail['hammer_storage_date'] ? date('Y-m-d', strtotime($detail['hammer_storage_date'])) : '-'; ?></td>
                                    <td><?php echo $detail['delivery_date'] ? date('Y-m-d', strtotime($detail['delivery_date'])) : '-'; ?></td>
                                    <td>
                                        <?php if ($_SESSION['role'] == 'admin'): ?>
                                            <button class="action-btn edit-btn" onclick="editDetail(<?php echo $detail['id']; ?>)">编辑</button>
                                            <button class="action-btn delete-btn" onclick="deleteDetail(<?php echo $detail['id']; ?>)">删除</button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="17" style="text-align: center;">暂无生产明细数据</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            <div class="pagination">
                <?php if ($total_pages > 1): ?>
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <a href="?page=<?php echo $i; ?>" class="page-link <?php echo $page == $i ? 'active' : ''; ?>">
                            <?php echo $i; ?>
                        </a>
                    <?php endfor; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script>
        function editDetail(id) {
            window.location.href = `edit_detail.php?id=${id}`;
        }

        function deleteDetail(id) {
            if (confirm('确定要删除这条记录吗？')) {
                fetch('delete_detail.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `id=${id}`
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('删除成功');
                        location.reload();
                    } else {
                        alert('删除失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('删除失败，请重试');
                });
            }
        }

        function updateStatus(id, status) {
            if (confirm('确定要更新状态吗？')) {
                fetch('update_status.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `id=${id}&status=${status}`
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        location.reload();
                    } else {
                        alert('状态更新失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('更新失败，请重试');
                });
            }
        }

        function updateChangeNumber(id, value) {
            if (confirm('确定要更新改号吗？')) {
                fetch('update_change_number.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `id=${id}&is_number_changed=${value}`
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        location.reload();
                    } else {
                        alert('改号更新失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('更新失败，请重试');
                });
            }
        }

        // 全选/取消全选
        function toggleAll(source) {
            const checkboxes = document.getElementsByClassName('row-checkbox');
            for (let checkbox of checkboxes) {
                checkbox.checked = source.checked;
                toggleRowHighlight(checkbox);
            }
        }

        // 切换行高亮
        function toggleRowHighlight(checkbox) {
            const row = checkbox.closest('tr');
            if (checkbox.checked) {
                row.classList.add('selected');
            } else {
                row.classList.remove('selected');
            }
        }

        // 为每个复选框添加点击事件
        document.addEventListener('DOMContentLoaded', function() {
            const checkboxes = document.getElementsByClassName('row-checkbox');
            for (let checkbox of checkboxes) {
                checkbox.addEventListener('change', function() {
                    toggleRowHighlight(this);
                });
            }
        });

        // 导出选中的记录
        function exportSelected() {
            const checkboxes = document.getElementsByClassName('row-checkbox');
            const selectedIds = [];
            
            for (let checkbox of checkboxes) {
                if (checkbox.checked) {
                    selectedIds.push(checkbox.value);
                }
            }

            if (selectedIds.length === 0) {
                alert('请至少选择一条记录');
                return;
            }

            // 创建一个虚拟表单并提交
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = 'export.php';

            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'ids';
            input.value = selectedIds.join(',');

            form.appendChild(input);
            document.body.appendChild(form);
            form.submit();
        }

        // 添加全选按钮到表格上方
        document.querySelector('.table-actions').insertAdjacentHTML('afterbegin', `
            <label style="margin-right: 15px; display: flex; align-items: center; gap: 4px;">
                <input type="checkbox" id="selectAll" onclick="toggleAll(this)">
                <span style="font-size: 13px;">全选</span>
            </label>
        `);

        function clearFilter() {
            window.location.href = 'index.php';
        }
    </script>
</body>
</html> 